<?php
namespace Service;

class Oss extends Base
{

    public function getUploadData($configKey = THE_DEFAULT)
    {
        $ossConfig = getConfig('oss', $configKey);
        $expire = time() + $ossConfig['expire'];
        $config = [
            'expiration' => date('Y-m-d\TH:i:s\Z', $expire),
            'conditions' => [
                ['content-length-range', 0, $ossConfig['max']],
                ['starts-with', '$key', $ossConfig['dir']]
            ]
        ];
        $policy = base64_encode(json_encode($config));
        /**/
        $callback = [
            'callbackUrl' => $ossConfig['callback_url'],
            'callbackBody' => 'bucket=${bucket}&object=${object}&etag=${etag}&size=${size}&mimeType=${mimeType}&imageInfoFormat=${imageInfo.format}&imageInfoWidth=${imageInfo.width}&imageInfoHeight=${imageInfo.height}&domain=${x:domain}&prefix=${x:prefix}&name=${x:name}&vw=${x:vw}&vh=${x:vh}',
            'callbackBodyType' => 'application/x-www-form-urlencoded'
        ];
        $callback = json_encode($callback);
        $callback = base64_encode($callback);
        /**/
        $response = [
            'OSSAccessKeyId' => $ossConfig['access_key_id'],
            'host' => $ossConfig['domain'],
            'dir' => $ossConfig['dir'],
            'expire' => $expire,
            'policy' => $policy,
            'callback' => $callback,
            'timestamp' => time(),
            'signature' => base64_encode(hash_hmac('sha1', $policy, $ossConfig['access_key_secret'], true))
        ];
        return $response;
    }

    /*
        验证回调请求确实是阿里云发起的
    */
    public function checkCallback($authorization, $publicKeyUrl, $requestUri, $body)
    {
        $ossConfig = getConfig('oss', THE_DEFAULT);
        $authorization = base64_decode($authorization);
        $publicKeyUrl = base64_decode($publicKeyUrl);
        $temp = parse_url($publicKeyUrl);
        if($temp['host'] != $ossConfig['public_key_url']){
            return false;
        }
        $publicKey = file_get_contents($publicKeyUrl);
        $result = openssl_verify(urldecode($requestUri) . "\n" . $body, $authorization, $publicKey, OPENSSL_ALGO_MD5);
        return $result == 1;
    }

}